<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>发送 POST 请求</title>
    <style>
      div {
        width: 400px;
        height: 300px;
        border: solid 1px #666;
      }
    </style>
  </head>
  <body>
    <div></div>
    <script>
        //获取 div 元素
        let div = document.querySelector('div');

        //绑定事件
        div.onmouseenter = function(){
            //1. 创建请求对象
            let xhr = new XMLHttpRequest();
            //2. 初始化 设置请求行
            xhr.open('post', 'http://127.0.0.1:8080/server/20');
            // //3. 发送  
            // 请求体  1. querystring   
            // xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); // 该类型用来表示 querystring 的格式类型
            // xhr.send('username=zhaowan&password=axybcd');
            //         2. JSON
            xhr.setRequestHeader('content-type', 'application/json');
            //声明数据对象
            let stu = {
                name: 'yundi',
                pass: '123123n1lk2j31lk'
            };
            xhr.send(JSON.stringify(stu));
            //4. 绑定事件
            xhr.onreadystatechange = function(){
                //判断
                if(xhr.readyState === 4){
                    div.innerHTML = xhr.response;
                }
            } 
        }

    </script>
  </body>
</html>
